package com.example.myapplication;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

public class AddAndEditActivity extends AppCompatActivity {
    Button backbtn;
    Button savebtn;
    Button deletabtn;
    TextView idvalue;
    ImageView thingimg;
    TextView datevalue;
    EditText thingname;
    Spinner type1;
    EditText count;
    Spinner unit;
    EditText position;
    EditText information;
    Button addType1;
    Button addUnit;

    Button countDe;
    Button countAdd;
    UserDAO dao;
    List<String> unitlist;
    List<String>type1list;
    ArrayAdapter unitAdapter;
    ArrayAdapter type1Adapter;
    Button takephoto;
    Button setphoto;
    String imagePath;
    Boolean isAdd;

    private static final int TAKE_PHOTO_REQUEST=1;
    private static final int GET_ALBUMM=2;
    Bitmap bitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //这个是获取布局文件的，这里是你下一个页面的布局文件//注意这个是跳转界面的不能设置错，应该是第一个
        setContentView(R.layout.activity_edit);
        init();

        dataProcess();
    }



    private void init() {
        dao=new UserDAO(this);

        imagePath="";

        unitlist=new ArrayList<>();
        type1list=new ArrayList<>();
        updateUnitlist();
        updateType1list();
        unitAdapter=new ArrayAdapter(this, androidx.appcompat.R.layout.support_simple_spinner_dropdown_item,unitlist);
        type1Adapter=new ArrayAdapter(this,androidx.appcompat.R.layout.support_simple_spinner_dropdown_item,type1list);

        backbtn=findViewById(R.id.btn_backtomainactivity);
        backbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        savebtn=findViewById(R.id.btn_savething);
        deletabtn=findViewById(R.id.btn_deletething);
        takephoto=findViewById(R.id.takephoto);
        setphoto=findViewById(R.id.setphoto);

        deletabtn.setEnabled(false);

        idvalue=findViewById(R.id.label_idvalue);
        thingimg=findViewById(R.id.thingimg);
        datevalue=findViewById(R.id.label_datevalue);
        thingname=findViewById(R.id.text_thingname);
        type1=findViewById(R.id.spinner_type1);
        type1.setAdapter(type1Adapter);
        count=findViewById(R.id.text_count);
        unit=findViewById(R.id.spinner_unit);
        unit.setAdapter(unitAdapter);
        unit.setSelection(0);
        position =findViewById(R.id.text_position);
        information=findViewById(R.id.text_infomation);

        takephoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                //startActivity(intent);
                startActivityForResult(intent,TAKE_PHOTO_REQUEST);
            }
        });
        setphoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, GET_ALBUMM);

            }
        });

        savebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(thingname.getText().toString().isEmpty()){
                    Toast.makeText(AddAndEditActivity.this,"物品名称不能为空",Toast.LENGTH_SHORT).show();
                }else{
                    if(bitmap!=null)
                        imagePath=BitmapUtils.saveBitmap(idvalue.getText().toString(),bitmap,AddAndEditActivity.this);
                    Thing thing=new Thing();
                    thing.setName(thingname.getText().toString());
                    thing.setCount(Integer.parseInt(count.getText().toString()));
                    thing.setTypeFirst(type1.getSelectedItemPosition()+1);
                    thing.setUnit(unit.getSelectedItemPosition()+1);
                    thing.setInformation(information.getText().toString());
                    thing.setPosition(position.getText().toString());
                    thing.setDatetime(System.currentTimeMillis());
                    thing.setImagePath(imagePath);
                    //根据id是否为空字符串或-1来判断，是保存新数据还是更新旧数据
                    if(isAddThing()){
                        dao.addThing(thing);
                    }
                    else{
                        thing.setId(Integer.parseInt(idvalue.getText().toString()));
                        dao.updateThing(thing);
                    }
                    finish();
                }
            }
        });
        deletabtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //删除指定id数据
                dao.deleteThing(Integer.parseInt(idvalue.getText().toString()));
                finish();
            }
        });

        countAdd=findViewById(R.id.btn_countAdd);
        countAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int c= Integer.parseInt(count.getText().toString());
                c=c+1;
                count.setText(String.valueOf(c));
            }
        });
        countDe=findViewById(R.id.btn_countDe);
        countDe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //if(count.getText().toString().equals("1"))return;
                int c= Integer.parseInt(count.getText().toString());
                c=c-1;
                count.setText(String.valueOf(c));
            }
        });
        count.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(editable.toString().isEmpty()||Integer.parseInt(editable.toString())==0){
                    countDe.setEnabled(false);
                }else
                    countDe.setEnabled(true);
            }
        });
        addUnit=findViewById(R.id.btn_addunit);
        addUnit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogshow("unit");
            }
        });
        addType1=findViewById(R.id.btn_addtype1);
        addType1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogshow("type1");
            }
        });


    }

    private boolean isAddThing() {
        return isAdd;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            if(requestCode==TAKE_PHOTO_REQUEST){
                Bundle bundle=data.getExtras();
                bitmap= (Bitmap) bundle.get("data");
                thingimg.setImageBitmap(bitmap);
            }
            if(requestCode==GET_ALBUMM){
                if (data!=null){
                    Uri uri=data.getData();
                    bitmap=BitmapUtils.uriToBitmap(uri,AddAndEditActivity.this);
                    thingimg.setImageBitmap(bitmap);
                }
            }
        }
    }

    private void dataProcess() {
        Bundle b=getIntent().getExtras();
        if(b!=null) {
            deletabtn.setEnabled(true);
            int thingid=(int)b.getSerializable("data");
            Thing thing=dao.queryThing(thingid);
            idvalue.setText(String.valueOf(thing.getId()));
            datevalue.setText(thing.getEditDate());
            bitmap=BitmapUtils.loadBitmap(thing.getImagePath());
            thingimg.setImageBitmap(bitmap);

            imagePath=thing.getImagePath();
            thingname.setText(thing.getName());
            count.setText(String.valueOf(thing.getCount()));
            if(thing.getTypeFirst()-1<type1list.size())
                type1.setSelection(thing.getTypeFirst()-1);
            else
                type1.setSelection(0);
            if(thing.getUnit()-1<unitlist.size())
                unit.setSelection(thing.getUnit()-1);
            else
                unit.setSelection(0);
            position.setText(thing.getPosition());
            information.setText(thing.getInformation());
            isAdd=false;
        }else {
            deletabtn.setEnabled(false);
            idvalue.setText(String.valueOf(dao.queryLastThingId()+1));
            isAdd=true;
        }
    }
    private void updateType1list() {
        type1list.clear();
        type1list.addAll(dao.queryType1All());
        if (type1Adapter!=null){
            type1Adapter.notifyDataSetChanged();
            type1.setSelection(type1list.size()-1);
        }
    }

    private void updateUnitlist() {
        unitlist.clear();
        //Log.d("输出", "updateUnitlist: 清空");
        unitlist.addAll(dao.queryUnitAll());
        //Log.d("输出", "updateUnitlist: "+unitlist.size());
        if (unitAdapter!=null){
            unitAdapter.notifyDataSetChanged();
            unit.setSelection(unitlist.size()-1);
        }
    }

    private void dialogshow(String dialogname) {
        View dialog_view=getLayoutInflater().inflate(R.layout.dialog_view,null);
        AlertDialog.Builder builder=new AlertDialog.Builder(AddAndEditActivity.this);
        //@SuppressLint({"MissingInflatedId", "LocalSuppress"})
        EditText itemtext=dialog_view.findViewById(R.id.text_newitem);
        switch (dialogname){
            case "unit":{
                builder.setTitle("添加新单位");
                itemtext.setHint("输入新单位");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //把数据保存到Unit表格中
                        dao.insertUnit(itemtext.getText().toString());
                        updateUnitlist();
                    }
                });
                break;
            }
            case "type1":{
                builder.setTitle("添加新类型");
                itemtext.setHint("输入新类型");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //把数据保存到表格中
                        dao.insertTypeFirst(itemtext.getText().toString());
                        updateType1list();
                    }
                });
                break;
            }
            default:
                break;
        }

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.setView(dialog_view);
        builder.create();
        builder.show();
    }

}
